<template>
    <div>
        <div class="banner" style="height: auto;top: 0;position: relative;margin-bottom: 8vw;">
            <img src="http://weixin.pbani.com/wx/static/images/view_device/banner.png" class="w100 pos_a"
                 style="opacity: .4;z-index: -1;top: 0;"/>
            <div class="flex"
                 style="justify-content: center;margin: 0 0 5vw; vertical-align:top; background: #BCC6E8;">
            <span style="margin-top: 5vw">
                <div @click="$emit(
                   'state',
                    {
                        page: 'demo'
                    }
                )" class="weui-btn weui-btn_mini weui-btn_primary">设备管理 </div>
                <img src="http://weixin.pbani.com/wx/static/images/left.png" style="margin-bottom:20px;"/>
                <span style="display:block;float:right;margin-top:5px;margin-left:5px;color:#FFA500">
                    绑定设备
                </span>
            </span>
            </div>

            <div class="flex" style="justify-content: center;">
                <div data-toggle="modal" data-target="#myModal" class="weui-btn weui-btn_mini weui-btn_primary">
                    {{devices.hasOwnProperty(userInfo['ctl'])
                    ? userInfo['devices'][userInfo['ctl']]['name'] : ''}}
                </div>
            </div>
            <div class="flex" style="justify-content: center;padding: 3vw 10vw 0 10vw">
                <img src="http://weixin.pbani.com/wx/static/images/view_device/locating.svg"
                     style="width:5vw;height: 5vw;"/>
                <span id="addr" style="color: blue">{{location_str}}</span>
            </div>
            <div class="flex" style="justify-content: center;margin-top: 2vw">
                <img src="http://weixin.pbani.com/wx/static/images/view_device/discovery_normal.svg"
                     style="width:5vw;height: 5vw;"/>
                <span style="color: blue" v-text="is_online? (screen_is_on?'使用中':'休眠中'):'不在线'"></span>
            </div>
        </div>

        <div class="div_boeder">
            <form action="activate_device" id="device_form">
                <div class="panel-group" id="accordion" style="padding: 0 5vw;">
                    <div class="panel panel-default" style="text-align: center;">
                        <div class="panel-heading">
                            <a data-toggle="collapse" data-parent="#accordion"
                               href="#collapseOne" style="color:#FFA500;font-weight:bold;">
                                设备监控
                            </a>
                        </div>
                        <div id="collapseOne" class="panel-collapse collapse">
                            <div class="panel-body1">
                                <div class="l">
                                    <div @click="voice_monitor"
                                         class="weui-btn weui-btn_mini weui-btn_primary purple">语音监听
                                    </div>
                                </div>
                                <div class="r">
                                    <span class="s1">单次支持设备端9秒录音监听</span>
                                </div>
                            </div>
                            <div
                                v-show="devices.hasOwnProperty(userInfo['ctl']) && devices[userInfo['ctl']]['type'] == 0"
                                class="panel-body1">
                                <div class="l">
                                    <div @click="screen_capture"
                                         class="weui-btn weui-btn_mini weui-btn_primary purple">一键截屏
                                    </div>
                                </div>
                                <div class="r">
                                    <span class="s1">单查看设备端当前屏幕界面</span>
                                </div>
                                <!--<img onclick="view_device.gallery_toggle($(this).attr('src'))"-->
                                <img v-if="ps_img" :src="ps_img"
                                     style="width: 10vw;height: 10vw"/>
                            </div>
                        </div>
                    </div>
                    <div class="panel panel-default"
                         v-if="devices.hasOwnProperty(userInfo['ctl']) && devices[userInfo['ctl']]['type']==0">
                        <div class="panel-heading" style="text-align: center;">
                            <div>
                                <a data-toggle="collapse" data-parent="#accordion"
                                   href="#collapseTwo" style="color:#FFA500;font-weight:bold;">
                                    模式设置
                                </a>
                            </div>
                        </div>
                        <div id="collapseTwo" class="panel-collapse collapse">
                            <div class="weui-cells weui-cells_radio" style="margin-top: 0">
                                <label class="weui-cell weui-check__label" for="x11" id="x11_label"
                                       @touchstart="changeModel('x11_label', 2)">
                                    <div class="weui-cell__bd">
                                        <div class="l">
                                            <span class="weui-btn weui-btn_mini weui-btn_primary purple">
                                                锁定模式
                                            </span>
                                        </div>
                                        <div class="r">
                                            <span class="s1">
                                                谨慎使用，设备锁定不可用
                                            </span>
                                        </div>
                                    </div>
                                    <div class="weui-cell__ft">
                                        <input type="radio" class="weui-check" name="mode_radio" id="x11" value="2">
                                        <span class="weui-icon-checked"></span>
                                    </div>
                                </label>
                                <label
                                    v-show="devices.hasOwnProperty(userInfo['ctl']) && devices[userInfo['ctl']]['type'] == 0"
                                    class="weui-cell weui-check__label" for="x12" id="x12_label"
                                    @touchstart="changeModel('x12_label', 1)">
                                    <div class="weui-cell__bd">
                                        <div class="l">
                                            <span class="weui-btn weui-btn_mini weui-btn_primary purple">
                                                限制模式
                                            </span>
                                        </div>
                                        <div class="r">
                                            <span class="s1">
                                                应用APP,仅白名单可用
                                            </span>
                                        </div>
                                    </div>
                                    <div class="weui-cell__ft">
                                        <input type="radio" name="mode_radio" class="weui-check" id="x12" value="1">
                                        <span class="weui-icon-checked"></span>
                                    </div>
                                </label>
                                <label class="weui-cell weui-check__label" for="x13" id="x13_label"
                                       @touchstart="changeModel('x13_label', 0)">
                                    <div class="weui-cell__bd">
                                        <div class="l">
                                            <span class="weui-btn weui-btn_mini weui-btn_primary purple">
                                            自由模式
                                        </span>
                                        </div>
                                        <div class="r">
                                            <span class="s1">
                                                默认，设备完全没有限制
                                            </span>
                                        </div>
                                    </div>
                                    <div class="weui-cell__ft">
                                        <input type="radio" name="mode_radio" class="weui-check" id="x13" value="0">
                                        <span class="weui-icon-checked"></span>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>


                    <div class="panel panel-default"
                         v-if="devices.hasOwnProperty(userInfo['ctl']) && devices[userInfo['ctl']]['type'] == 1">
                        <div class="panel-heading" style="text-align: center;">
                            <div>
                                <a data-toggle="collapse" data-parent="#accordion"
                                   href="#collapseThreewo" style="color:#FFA500;font-weight:bold;"
                                   @click="send_family_pic">
                                    发送照片
                                </a>
                            </div>
                        </div>
                    </div>

                </div>
                <div class="page gallery" id="gallery" style="display: none">
                    <div class="page__hd">
                        <h1 class="page__title">Gallery</h1>
                        <p class="page__desc">画廊，可实现上传图片的展示或幻灯片播放</p>
                    </div>
                    <div class="weui-gallery" style="display: block">
                <span class="weui-gallery__img"
                      style="background-image: url('http://weixin.pbani.com/wx/static/images/view_device/discovery_normal.svg');"></span>
                        <div class="weui-gallery__opr" style="padding: 4vw;">
                            <div @click="gallery_toggle" class="weui-gallery__del">
                                <i class="weui-icon-clear"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- 模态框（Modal） -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;
                        </button>
                        <h4 class="modal-title" id="myModalLabel">
                            设备名修改
                        </h4>
                    </div>
                    <div class="modal-body">
                        <input class="form-control" type="text" name="change_nick_name" v-model="change_name"
                               placeholder="昵称修改">
                    </div>
                    <div class="modal-footer">
                        <button type="button" id="close" class="btn btn-default" data-dismiss="modal">关闭
                        </button>
                        <button type="button" @click="updateDeviceInfo" class="btn btn-primary">
                            提交更改
                        </button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal -->
        </div>
    </div>
</template>

<script>
    import {http} from "../../static/js/common";

    export default {
        props: ['userInfo', 'devices', 'geoc', 'ps_img'],
        data() {
            return {
                last_point_info: [],
                change_name: '',
                is_online: false,
                screen_is_on: true,
                is_can_screen_capture: false,
                location_str: '',
                m_last_point: {},
                device_status: 0
            }
        },
        computed: {
            last_point: {
                get() {
                    return this.m_last_point;
                },
                set(obj) {
                    if (obj.hasOwnProperty('address') && obj['address']) {
                        this.location_str = obj['address'] + '';
                        if (!this.location_str) {
                            $.alert(JSON.stringify(obj));
                        }
                        return;
                    }

                    let arr = obj['point'];
                    this.m_last_point = arr;
                    let lon = arr[0];
                    let lat = arr[1];
                    // let point = new BMap.Point(lon, lat);
                    // this.geoc.getLocation(point, (rs) => {
                    //     //addressComponents对象可以获取到详细的地址信息
                    //     let addComp = rs.addressComponents;
                    //     let site = addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                    //     console.log(addComp)
                    //     console.log(site)
                    //     this.location_str = site + '';
                    //
                    //     if (!this.location_str) {
                    //         $.alert(JSON.stringify(addComp));
                    //     }
                    // });

                    setTimeout(() => {
                        let device_type;
                        if (this.device.hasOwnProperty('type')) {
                            device_type = this.device['type']
                        } else {
                            device_type = 0
                        }


                        var piObj = {
                            x_PI: 3.14159265358979324 * 3000.0 / 180.0,
                            PIs: 3.1415926535897932384626,
                            a: 6378245.0,
                            ee: 0.00669342162296594323
                        };

                        /**
                         * 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
                         * 即 百度 转 谷歌、高德
                         * @param bd_lon
                         * @param bd_lat
                         * @returns {*[]}
                         */
                        function DbToGc(bd_lon, bd_lat) {
                            var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
                            var x = bd_lon - 0.0065;
                            var y = bd_lat - 0.006;
                            var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
                            var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
                            var gg_lng = z * Math.cos(theta);
                            var gg_lat = z * Math.sin(theta);
                            return [gg_lng, gg_lat]
                        }

                        /**
                         * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
                         * 即谷歌、高德 转 百度
                         * @param lng
                         * @param lat
                         * @returns {*[]}
                         */
                        function gcToDb(lng, lat) {
                            var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * piObj.x_PI);
                            var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * piObj.x_PI);
                            var bd_lng = z * Math.cos(theta) + 0.0065;
                            var bd_lat = z * Math.sin(theta) + 0.006;
                            return [bd_lng, bd_lat]
                        }

                        /**
                         * WGS84转GCj02
                         * @param lng
                         * @param lat
                         * @returns {*[]}
                         */
                        function wgsToGc(lng, lat) {
                            // var lnglat = retConfirmNum (lng, lat);
                            // lng = lnglat[0];
                            // lat = lnglat[1];
                            var dlat = transformlat(lng - 105.0, lat - 35.0);
                            var dlng = transformlng(lng - 105.0, lat - 35.0);
                            var radlat = lat / 180.0 * piObj.PIs;
                            var magic = Math.sin(radlat);
                            magic = 1 - piObj.ee * magic * magic;
                            var sqrtmagic = Math.sqrt(magic);
                            dlat = (dlat * 180.0) / ((piObj.a * (1 - piObj.ee)) / (magic * sqrtmagic) * piObj.PIs);
                            dlng = (dlng * 180.0) / (piObj.a / sqrtmagic * Math.cos(radlat) * piObj.PIs);
                            var mglat = lat + dlat;
                            var mglng = lng + dlng;
                            return [mglng, mglat];
                        }

                        /**
                         * GCJ02 转换为 WGS84
                         * @param lng
                         * @param lat
                         * @returns {*[]}
                         */
                        function gcToWgs(lng, lat) {
                            var lnglat = retConfirmNum(lng, lat);
                            lng = lnglat[0];
                            lat = lnglat[1];
                            var dlat = transformlat(lng - 105.0, lat - 35.0);
                            var dlng = transformlng(lng - 105.0, lat - 35.0);
                            var radlat = lat / 180.0 * piObj.PIs;
                            var magic = Math.sin(radlat);
                            magic = 1 - piObj.ee * magic * magic;
                            var sqrtmagic = Math.sqrt(magic);
                            dlat = (dlat * 180.0) / ((piObj.a * (1 - piObj.ee)) / (magic * sqrtmagic) * piObj.PIs);
                            dlng = (dlng * 180.0) / (piObj.a / sqrtmagic * Math.cos(radlat) * piObj.PIs);
                            mglat = lat + dlat;
                            mglng = lng + dlng;
                            return [lng * 2 - mglng, lat * 2 - mglat]
                        }

                        function transformlat(lng, lat) {
                            var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
                            ret += (20.0 * Math.sin(6.0 * lng * piObj.PIs) + 20.0 * Math.sin(2.0 * lng * piObj.PIs)) * 2.0 / 3.0;
                            ret += (20.0 * Math.sin(lat * piObj.PIs) + 40.0 * Math.sin(lat / 3.0 * piObj.PIs)) * 2.0 / 3.0;
                            ret += (160.0 * Math.sin(lat / 12.0 * piObj.PIs) + 320 * Math.sin(lat * piObj.PIs / 30.0)) * 2.0 / 3.0;
                            return ret
                        }

                        function transformlng(lng, lat) {
                            var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
                            ret += (20.0 * Math.sin(6.0 * lng * piObj.PIs) + 20.0 * Math.sin(2.0 * lng * piObj.PIs)) * 2.0 / 3.0;
                            ret += (20.0 * Math.sin(lng * piObj.PIs) + 40.0 * Math.sin(lng / 3.0 * piObj.PIs)) * 2.0 / 3.0;
                            ret += (150.0 * Math.sin(lng / 12.0 * piObj.PIs) + 300.0 * Math.sin(lng / 30.0 * piObj.PIs)) * 2.0 / 3.0;
                            return ret
                        }


                        if (device_type == 0) {
                            AMap.convertFrom([lon, lat], "baidu", (status, result) => {
                                this.last_point_info = [result.locations[0].lng, result.locations[0].lat]
                                this.afterCenter()
                            });
                        } else {
                            var lnglat = wgsToGc(lon, lat); //WGS84转GCj02
                            this.last_point_info = [lnglat[0], lnglat[1]]
                            this.afterCenter()
                        }

                    }, 3000);
                }

            }
        },
        methods: {
            afterCenter() {
                let lon = this.last_point_info[0],
                    lan = this.last_point_info[1];

                let url = `http://restapi.amap.com/v3/geocode/regeo?key=您的key&location=${lon},${lan}&poitype=&radius=300&extensions=base&batch=false&roadlevel=0`

                http({
                    url: url
                }).then(data => {
                    console.log(data);
                    if (data.status === 1) {
                        this.location_str = data.regeocode.formatted_address + '';
                        if (!this.location_str) {
                            $.alert(JSON.stringify(addComp));
                        }
                    } else {
                    }
                });
            },
            updateDeviceInfo() {
                console.log(this.change_name);

                if (!this.change_name) {
                    return
                }

                console.log(this.userInfo)
                console.log(this.userInfo.ctl)
                console.log(this.devices)

                http({
                    url: "update_device_info",
                    param: {
                        device_name: this.change_name,
                        sn: this.userInfo.ctl,
                    }
                }).then((data) => {
                    if (data.err === 0) {
                        this.userInfo['devices'][this.userInfo['ctl']]['name'] = this.change_name;
                        this.change_name = "";
                        $.alert("修改成功", "设备名以修改，点击确定返回。", () => {
                        });
                        // $("#close").trigger("click")
                    } else {
                    }
                });
            },
            gallery_toggle(url) {
                if (typeof url === 'undefined') {
                    $('#gallery').hide()
                } else {
                    $('#gallery .weui-gallery__img').css(
                        'background-image',
                        'url(' + url + ')'
                    );
                    $('#gallery').show()
                }
            },
            voice_monitor() {
                http({
                    url: "voice_monitor",
                    param: {
                        sn: this.userInfo['ctl'],
                        device_type: this.devices[this.userInfo['ctl']]['type']
                    }
                }).then(data => {
                    if (data.err === 0) {
                        $.alert("成功", "语音监听命令下发成功，确定返回。", function () {
                        });
                    } else {
                        $.alert(data.msg, function () {
                        });
                    }
                });
            },
            send_family_pic() {
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    // sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
                    success: (res) => {
                        let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        let id = localIds[0];
                        if (id) {
                            wx.uploadImage({
                                localId: id, // 需要上传的图片的本地ID，由chooseImage接口获得
                                isShowProgressTips: 1, // 默认为1，显示进度提示
                                success: (res) => {
                                    http({
                                        url: "tmp_img",
                                        param: {
                                            device_type: this.devices[this.userInfo['ctl']]['type'],
                                            sn: this.devices[this.userInfo['ctl']]['sn'],
                                            server_id: res.serverId,
                                        }
                                    }).then(data => {
                                        $.alert("success");
                                        // if (data.err === 0) {
                                        //     this.talk_list.push({
                                        //         type: 3,
                                        //         content: data.url,
                                        //         sender: token
                                        //     })
                                        // }
                                    });
                                }
                            });
                        }
                    }
                });
            },
            get_device_status() {
                http({
                    url: "device_status",
                    param: {
                        sn: this.userInfo['ctl']
                    }
                }).then(data => {
                    if (data.err === 0) {
                        this.device_status = data.status;
                        $("input[name=mode_radio][value=" + this.device_status + "]").attr('checked', 'checked');
                    } else {
                        // $.alert("警告", "设备状态异常。", function () {
                        //     //location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx54f681abc539d055&redirect_uri=http%3A%2F%2Faa0125e8.ngrok.io%2Fauth&response_type=code&scope=snsapi_base&state=STATE"
                        // });
                    }
                });
            },
            changeScreen(id, mode) {
                http({
                    url: `change_screen`,
                    param: {
                        sn: this.userInfo['ctl'],
                        mode: mode
                    }
                }).then(data => {
                    if (data.err === 0) {
                        $.alert("成功", "屏幕设置成功，确定返回。", function () {
                            setTimeout(() => {
                                this.get_device_status();
                            }, 1000);
                            $(`#${id}`).trigger('click');
                        });
                    } else {
                        $.alert(data.msg, () => {
                        });
                    }
                });
            },
            set_model(mode) {
                mode = parseInt(mode);
                let id;
                switch (mode) {
                    case 0:
                        id = 'x13_label';
                        break;
                    case 1:
                        id = 'x12_label';
                        break;
                    default:
                        id = 'x11_label';
                        break;
                }
                $(`#${id}`).trigger('click');
            },
            init_status() {
                http({
                    // url: 'device_is_online',
                    url: 'device_status',
                    param: {
                        sn: this.userInfo['ctl']
                    }
                }).then(data => {
                    this.is_online = !!data['is_online'];
                    if (parseInt(this.devices[this.userInfo['ctl']]['type']) === 1) {
                        this.screen_is_on = true
                    } else {
                        this.screen_is_on = !!data['screen_is_on']
                    }
                    let mode = parseInt(data['model_val']);
                    let id;
                    switch (mode) {
                        case 0:
                            id = 'x13_label';
                            break;
                        case 1:
                            id = 'x12_label';
                            break;
                        default:
                            id = 'x11_label';
                            break;
                    }
                    $(`#${id}`).trigger('click');
                });
            },
            changeModel(id, mode) {
                http({
                    url: "lock_device",
                    param: {
                        sn: this.userInfo['ctl'],
                        mode: mode
                    }
                }).then(data => {
                    if (data.err === 0) {
                        $.alert("成功", "模式设置中。")
                    } else {
                        $.alert(data.msg, () => {
                        });
                    }
                });
            },
            screen_capture() {
                http({
                    url: "screen_capture",
                    param: {
                        sn: this.userInfo['ctl']
                    }
                }).then(data => {
                    if (data.err === 0) {
                        $.alert("成功", "一键截屏命令下发成功，确定返回。", function () {
                        });
                    } else {
                        $.alert(data.msg, function () {
                        });
                    }
                });

            }
        },
        created() {
            console.log(this.userInfo['ctl'])
            console.log(this.devices)
            if (!this.userInfo['ctl']) {
                this.$emit(
                    'state',
                    {
                        page: 'demo'
                    }
                );
                return;
            }

            this.init_status();

            http({
                url: "get_points",
                param: {
                    limit: 1
                }
            }).then(data => {
                console.log(data.list);
                if (!data.list) {
                    return;
                }

                if (data.list.length <= 0) {
                    return
                }
                this.last_point = data.list[0];
                console.log(this.last_point)
            });
            // http({
            //     url: "device_status",
            //     param: {
            //         sn: this.userInfo['ctl']
            //     }
            // }).then(data => {
            //     if (data.err === 0) {
            //         $("input[name=mode_radio][value=" + data.status + "]").attr('checked', 'checked');
            //         if (data.lock === 0) {
            //             $("input[name=screen_radio][value=" + 2 + "]").attr('checked', 'checked');
            //         } else {
            //             $("input[name=screen_radio][value=" + 1 + "]").attr('checked', 'checked');
            //         }
            //         if (data.status === 2) {
            //             $("#screen_block").show();
            //         } else {
            //             $("#screen_block").hide();
            //         }
            //     } else {
            //         // $.alert("警告", "设备状态异常。", function () {
            //         // });
            //     }
            // });
        },
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .panel-heading a {
        text-decoration: none;
        display: block;
    }

    .panel-body1 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 2vw;
    }

    .panel-body1 > div {
        display: inline-block;
    }

    .panel-body1 > div.l {
        padding: 1vw 0;
        width: 45%;
    }

    .panel-body1 > div.r {
        width: 59%;
        padding-right: 10vw;
    }

    .s1 {
        font-size: 3vw;
        color: blue;
        /*padding-bottom: 3vw;*/
    }

    .div_boeder {
        margin: 5px auto;
    }

    td {
        color: #DAA520;
    }

    .purple {
        font-size: 3.5vw;
        background-color: #9C27B0;
    }

    .weui-cell__bd {
        width: 70vw;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 2vw;
    }

    .weui-cell__bd > div {
        display: inline-block;
    }

    .weui-cell__bd > div.l {
        padding: 1vw 0;
        width: 45%;
    }

    .weui-cell__bd > div.r {
        width: 65%;
        padding-right: 1vw;
        line-height: 1;
    }
</style>
